<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form"  label-position="right" label-width="auto">
            <EdCreateCard :title="isUpdate ? '编辑广告' : '添加广告'">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_auto">
                    <el-form-item label="广告图名称" class="block" prop="title" :rules="$validate.validates({required:true,msg:'广告图名称不能为空'})">
                        <el-input style="max-width: 600px" v-model="form.title" placeholder="请输入广告图名称" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="点击跳转至" prop="linkType" class="itemRadioBlock block" :rules="rules.linkType">
                        <el-radio-group @change="changeTimeRadio" v-model="form.linkType">
                            <el-radio :label="1" class="block marginBottom12">店铺
                                <el-select
                                        v-model="value"
                                        filterable
                                        remote
                                        :disabled="form.linkType != 1"
                                        class="inputWidth224 marginLeft20"
                                        reserve-keyword
                                        @change="changeShop"
                                        placeholder="请输入店铺名称"
                                        :remote-method="remoteMethod"
                                        :loading="loading">
                                    <el-option
                                            v-for="item in shopOptions"
                                            :label="item.merchantName"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-radio>
                            <el-radio :label="2" class="block marginBottom12">商品
                                <el-select
                                        v-model="value1"
                                        filterable
                                        remote
                                        :disabled="form.linkType != 2"
                                        class="inputWidth224 marginLeft20"
                                        reserve-keyword
                                        @change="changeCom"
                                        placeholder="请输入商品名称"
                                        :remote-method="remoteMethodCom"
                                        :loading="loading">
                                    <el-option
                                            v-for="item in comOptions"
                                            :key="item.id"
                                            :label="item.productName"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-radio>
                            <el-radio :label="3" class="block">链接
                                <el-input placeholder="请输入链接" :disabled="form.linkType != 3" v-model="form.linkChange" style="width: 75%;margin-left: 20px;"></el-input>
                            </el-radio>
                            <el-radio :label="0" class="block">不跳转</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="广告图片" class="block" prop="pic" :rules="$validate.validates({required:true,msg:'广告图片不能为空'})">
                        <el-upload
                                class="business-uploader-single-313"
                                :action="action"
                                :headers="headers"
                                style="margin-top: 0"
                                accept="image/*"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <el-image v-if="form.pic" :src="form.pic" fit="contain"></el-image>
                            <div v-else>
                                <i class="el-icon-plus avatar-uploader-icon"></i>
                                <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65); margin: 10px 0 12px 0;line-height: 1">上传图片</div>
                                <div style="font-size: 14px;color: rgba(0, 0, 0, 0.65);line-height: 1">大小不超过2M</div>
                            </div>
                        </el-upload>
                    </el-form-item>
                    <el-form-item class="paddingBottom145 block" >
                        <el-button class="ed-button ed_black-bottom" @click="onSubmit('formRef')" :loading="disabled">保存</el-button>
                        <el-button class="ed-button ed_white_bottom" @click="reset">重置</el-button>
                    </el-form-item>
                </div>
            </EdCreateCard>
        </el-form>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import {validURL2} from 'src/utils/validate'
    import {getToken} from 'src/utils/auth'
    // import {merchantList ,productList ,adAdd,getadvertiseDetail} from "src/api/shoppingMall";
    import {merchantList ,productList ,adAdd,getadvertiseDetail} from "./api";
    export default {
        name: "AdvertisementCreate",
        components: { EdCreateCard },
        data(){
            const validateJump = (rule,value,callback) => {
                if(value == 0){
                    callback()
                }else if(value == 1) {
                    if(this.value){
                        callback()
                    } else {
                        callback(new Error("请输入店铺"))
                    }
                } else if(value == 2) {
                    if(this.value1){
                        callback()
                    } else {
                        callback(new Error("请输入商品"))
                    }

                } else if(value == 3) {
                    if(this.form.linkChange){
                        if(validURL2(this.form.linkChange)){
                            callback()
                        } else {
                            callback(new Error("请输入正确的跳转链接"))
                        }
                    } else {
                        callback(new Error("请输入跳转链接"))
                    }
                } else {
                    callback(new Error("请选择跳转类型"))
                }
            }
            return{
                rules: {
                    linkType: [
                        { required: true,validator: validateJump, trigger: 'blur' },
                    ]
                },
                form:{
                    title:"",
                    linkType:"",
                    link:"",
                    linkName:"",
                    pic:"",
                    linkChange:''
                },
                disabled:false,
                action:"",
                headers:{
                    RdAuthorization: getToken()
                },
                shopOptions:[],
                shopOptionsList:[],
                comOptions:[],
                comOptionsList:[],
                thirdUrl:[],
                loading:false,
                value:"",
                value1:"",
                link:'',
                isUpdate:false,
                // 重置后保证id不要被清空,因为编辑跟新增是调的同一个接口，编辑的时候要将id传过去
                resetId:''
            }
        },
        activated(){
            this.action = this.$baseApi + "/file/upload";
            // 判断一下是否是根据id传过来的参数，如果是就是点击编辑按钮
            if(this.$route.query.id){
                this.isUpdate=true;
                this.getadvertiseDetail()
            }else{
                this.isUpdate = false
            }
        },
        deactivated() {
            this.form = {
                title:"",
                linkType:"",
                link:"",
                linkName:"",
                pic:"",
                linkChange:''
            }
            this.value='',
            this.value1='',
            this.link = '',
            this.shopOptions=[],
            this.shopOptionsList=[],
            this.comOptions=[],
            this.comOptionsList=[],
            this.thirdUrl=[],
            // this.multipleSelection=[]
            this.$refs['formRef'].resetFields();
        },
        methods:{
            changeShop(val){
              let opt =  this.shopOptions.find((item)=>{
                    return item.id == val
                })
                this.form.linkName = opt.merchantName;
                this.form.link = opt.id
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.merchantList(query);
                } else {
                    this.shopOptions = [];
                    this.value=''
                }
            },
            merchantList(query){
                merchantList({merchantName:query,page: 1, pageSize: 999}).then(response => {
                    if(response.code == 20000) {
                        this.shopOptions = response.data.records.map(x=>{return {id:x.id,merchantName:x.merchantName}});
                        this.loading = true;
                    }
                }).finally(() => this.loading = false)
            },
            changeCom(val){
                const opt = this.comOptions.find((item) => {
                    return item.id == val
                })
                if (opt) {
                    this.form.linkName = opt.productName;
                    this.form.link = opt.id
                }
            },
            remoteMethodCom(query){
                if (query !== '') {
                   this.productList(query)
                } else {
                    this.comOptions = [];
                    this.value1=''
                }
            },
            productList(query){
                productList({name:query,page: 1, pageSize: 999}).then(response => {
                    if(response.code == 20000) {
                        this.comOptions = response.data;
                        this.loading = true;
                    }
                }).finally(() => this.loading = false)
            },
            changeTimeRadio(val){
                console.log('val',val);
                if(val == 1){
                    this.form.linkChange = "",
                    this.value1 = ""
                    this.comOptions=[]
                }
                if(val == 2){
                    this.form.linkChange = "",
                    this.value = "" 
                    this.shopOptions=[] 
                }
                if(val == 3){
                    this.value1 = ""
                    this.value = ""
                }
                if(val == 0){
                    this.value1 = ""
                    this.value = ""
                    this.form.linkChange = ""
                }
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.disabled = true;
                        window.setTimeout(() => {
                            this.disabled = false
                        }, 2000);
                        if(this.isUpdate){
                            adAdd(this.form).then(response => {
                                if(response.code == 20000) {
                                    this.$message.success({
                                        message: '编辑广告成功 即将返回广告列表',
                                        duration: 2000,
                                        center:true
                                    });
                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }
                            })
                        } else {
                            adAdd(this.form).then(response => {
                                if(response.code == 20000) {
                                    this.$message.success({
                                        message: '新增广告成功 即将返回广告列表',
                                        duration: 2000,
                                        center:true
                                    });
                                    window.setTimeout(() => {
                                        this.$utilsSet.goBack(this.$router);
                                    }, 600)
                                }
                            })
                        }
                        
                    }
                })
            },
            getadvertiseDetail(){
                getadvertiseDetail({id:this.$route.query.id}).then(response => {
                    if(response.success) {
                        this.$set(this.$data, 'form',{...response.data,})
                        // this.form.linkChange = response.data.link
                        if(response.data.linkType==2){
                            this.value1 = response.data.linkName
                        }
                        if(response.data.linkType==1){
                            this.value = response.data.linkName
                        }
                        if(response.data.linkType==3){
                            this.linkChange = response.data.linkChange
                        }
                    }
                })
            },
            reset(){
                this.form = {
                    title:"",
                    linkType:"",
                    link:"",
                    linkName:"",
                    pic:"",
                    linkChange:'',
                    id:this.$route.query.id
                };
                this.value='',
                this.value1='',
                this.link = '',
                this.shopOptions=[],
                this.shopOptionsList=[],
                this.comOptions=[],
                this.comOptionsList=[],
                this.thirdUrl=[],
                this.$refs.formRef.resetFields()
            },
            handleAvatarSuccess(file){
                if(file.code == 20000){
                    this.form.pic = file.data;
                }else {
                    this.$message.error({
                        message: file.message,
                        center: true,
                        duration: 2000,
                    })
                }
            },
            beforeAvatarUpload(file){
                // const fileType = file.name.split('.');
                // const fileDate = fileType.slice(-1);
                // if (['jpeg', 'jpg', 'png'].indexOf(fileDate[0]) < 0) {
                //     // this.$message.error('仅支持格式：.jpeg、.jpg、.png!');
                //     this.$message.error({
                //         message:'仅支持格式：.jpeg、.jpg、.png!',
                //         center:true,
                //         duration:2000
                //     });
                //     return false
                // }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    // this.$message.error('上传文件大小不能超过 2MB!');
                    this.$message.error({
                        message:"上传文件大小不能超过 2MB!",
                        center:true,
                        duration:2000
                    });
                }
                return isLt2M;
            },
        }
    }
</script>

<style lang="scss">

</style>